<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 管理员列表 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-button type="primary" @click="handleAdd()">新增管理员</el-button>
            <el-table :data="tableData.data" border class="table" ref="multipleTable"
                header-cell-class-name="table-header" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="" label="ID" width="100" align="center"><template slot-scope="scope">{{
                        scope.$index + 1
                }}</template></el-table-column>
                <el-table-column prop="account" label="账号" align="center"></el-table-column>

                <el-table-column prop="roleName" label="角色" align="center"></el-table-column>

                <el-table-column label="订单状态" align="center">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.status == 'n'" type="danger"> 锁定 </el-tag>
                        <el-tag v-if="scope.row.status == 'N'" type="danger"> 锁定 </el-tag>
                        <el-tag v-if="scope.row.status == 'y'" type="success"> 正常 </el-tag>
                        <el-tag v-if="scope.row.status == 'Y'" type="success"> 正常 </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">更改
                        </el-button>
                        <!-- <el-button type="text" icon="el-icon-delete" class="red"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background layout="total, prev, pager, next" :current-page="tableData.currPage"
                    :page-size="tableData.currPageSize" :total="tableData.totalPages"
                    @current-change="handlePageChange"></el-pagination>
            </div>
        </div>

        <!-- 更新弹出框 -->
        <el-dialog title="更新" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="账号">
                    <el-input v-model="form.account"></el-input>
                </el-form-item>

                <el-form-item label="角色">
                    <el-select @change="handleSelectChange(form.roleId)" v-model="form.roleId" placeholder="状态">
                        <el-option v-for="role in allRole" :key="role.id" :label="role.name" :value="role.id">
                        </el-option>
                    </el-select>
                </el-form-item>


                <el-form-item label="菜单列表">
                    <el-tree :data="menus" :default-expand-all="false" :props="menuDefaultProps">
                    </el-tree>
                </el-form-item>

                <el-form-item label="分配权限">
                    <el-tree :data="perms" :default-expand-all="false" :props="permDefaultProps">
                    </el-tree>
                </el-form-item>

                <el-form-item label="状态">
                    <el-radio v-model="form.status" label="n">锁定</el-radio>
                    <el-radio v-model="form.status" label="y">正常</el-radio>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">提 交</el-button>
            </span>
        </el-dialog>

        <!-- 新增弹出框 -->
        <el-dialog title="新增" :visible.sync="addVisible" width="30%">
            <el-form ref="form" :model="manager" label-width="70px">
                <el-form-item label="账号">
                    <el-input placeholder="请输入账号" v-model="manager.account"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input placeholder="请输入密码" v-model="manager.password" show-password></el-input>
                </el-form-item>
                <el-form-item label="角色">
                    <el-select @change="handleSelectChange(manager.roleId)" v-model="manager.roleId"
                        placeholder="请选择角色">
                        <el-option v-for="role in allRole" :key="role.id" :label="role.name" :value="role.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="菜单列表">
                    <el-tree :data="menus" :default-expand-all="false" :props="menuDefaultProps">
                    </el-tree>
                </el-form-item>

                <el-form-item label="分配权限">
                    <el-tree :data="perms" :default-expand-all="false" :props="permDefaultProps">
                    </el-tree>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="addEdit">提 交</el-button>
            </span>
        </el-dialog>


    </div>
</template>

<script>
import { fetchData } from '../../api/index';
export default {
    name: 'basetable',
    data() {
        return {
            msg: "",
            query: {
                address: '',
                name: '',
                pageIndex: 1,
                pageSize: 10
            },
            manager: {
                account: "",
                password: "",
                roleId: ""
            },
            tableData: [],
            allRole: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            addVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            //-------树形图,父子层级参照依据-------
            menus: [],
            perms: [],
            menuDefaultProps: {
                children: 'subMenu',
                label: 'name'
            },
            permDefaultProps: {
                children: 'subPerm',
                label: 'name'
            }
            //-------树形图，父子层级参照依据-------
        };
    },
    created() {
        this.getData(1);
    },
    methods: {
        // 获取管理员列表
        getData(pageNum) {
            this.$axios.get("/admin/manager/list?pageNum=" + pageNum).then(r => {
                if (r.data.code == "200") {
                    this.tableData = r.data.data;
                } else {
                    console.log("code:" + r.data.code);
                    alert("系统维护中！")
                }
            });

            this.$axios.get("/admin/role/list").then(r => {
                if (r.data.code == "200") {
                    this.allRole = r.data.data;
                } else {
                    console.log("code:" + r.data.code);
                    alert("系统维护中！")
                }
            })
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.$message.success('删除成功');
                    this.tableData.splice(index, 1);
                })
                .catch(() => { });
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = row;

            this.getMenusAndPermsByRoleId(row.roleId);

            this.editVisible = true;
        },
        //新增操作
        handleAdd() {
            this.addVisible = true;
        },
        handleSelectChange(id) {
            this.getMenusAndPermsByRoleId(id);
        },
        //查询角色的菜单和权限列表
        getMenusAndPermsByRoleId(roleId) {
            //获取菜单列表
            this.$axios.get("/findMenus/" + roleId).then(r => {
                let menus = r.data.data;
                let menusTree = [];
                //将菜单列表排好父子层级
                for (let pm of menus) {
                    if (pm.pid == null) {
                        //设置父菜单的所有子菜单
                        pm.subMenu = [];
                        for (let sm of menus) {
                            if (sm.pid == pm.id) {
                                pm.subMenu.push(sm);
                            }
                        }
                        menusTree.push(pm);
                    }
                }
                this.menus = menusTree;
            })

            //获取权限列表
            this.$axios.get("/perm/findPerms/" + roleId).then(r => {
                let perms = r.data.data;
                let permsTree = [];
                //将权限列表排好父子层级
                for (let pp of perms) {
                    if (pp.pid == null) {
                        //设置父权限的所有子权限
                        pp.subPerm = [];
                        for (let sp of perms) {
                            if (sp.pid == pp.id) {
                                pp.subPerm.push(sp);
                            }
                        }
                        permsTree.push(pp);
                    }
                }
                this.perms = permsTree;
            })

        },
        // 保存编辑
        saveEdit() {
            this.editVisible = false;
            this.$message.success(`修改第 ${this.idx + 1} 行成功`);
            this.$set(this.tableData, this.idx, this.form);
            console.log(this.form);

            this.$axios.post("/admin/manager/update", this.form).then(r => {
                if (r.data.code == "200") {
                    alert("更新成功");
                } else {
                    console.log("code:" + r.data.code);
                    alert("系统维护中！")
                }
            })

        },
        addEdit() {
            this.addVisible = false;
            this.$set(this.manager);
            console.log(this.manager);
            if (this.manager.account == null || this.manager.account.trim() == "") {
                alert("账号不能为空");
            } else if (this.manager.password == null || this.manager.password.trim() == "") {
                alert("密码不能为空");
            } else if (this.manager.roleId == null || this.manager.roleId <= 0) {
                alert("角色不能为空");
            } else {
                this.$axios.post("/admin/manager/add", this.manager).then(r => {
                    if (r.data.code == "200") {
                        alert("新增成功");
                        this.getData(1);
                    } else if (r.data.code == "501") {
                        alert(r.data.message);
                    } else {
                        console.log("code:" + r.data.code);
                        alert("系统维护中！")
                    }
                })
            }
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        }



    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}

.red {
    color: #ff0000;
}

.mr10 {
    margin-right: 10px;
}

.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
